package iscript.gameFramework.GameLite.content 
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.core.LoaderCore;
	import com.greensock.loading.data.LoaderMaxVars;
	import com.greensock.loading.data.SWFLoaderVars;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.LoaderStatus;
	import com.greensock.loading.SWFLoader;
	import flash.utils.Dictionary;
	import iscript.gameFramework.GameLite.events.GameContentEvent;

	internal class SwfContent implements IGameContent
	{
		
		private var _data:Dictionary = new Dictionary();	
		private var _loaderMax:LoaderMax;
		private var _gameContent:GameContent;

		
		
		public function SwfContent(gameContent:GameContent) 
		{
			   _gameContent = gameContent
			   var loadvars:LoaderMaxVars = new LoaderMaxVars();
				   loadvars.autoLoad(true);
				   loadvars.maxConnections(3);
				   loadvars.onChildComplete(_onChildCompleteLogic)
				   _loaderMax = new LoaderMax(loadvars);
				   _loaderMax.load();
		}
		
		private function _onChildCompleteLogic(e:LoaderEvent):void 
		{
			  _dispatch(SWFLoader(e.target));
		}		
		
		private function _dispatch(load:SWFLoader):void {
			   var swfload:SWFLoader = load;
			   var event:GameContentEvent = new GameContentEvent(GameContentEvent.ONLOADSWF);
			       event.content =  swfload;
				   event.key = swfload.vars[GameContent.GamneContentKey];
			       _gameContent.dispatchEvent(event);
				   
				 var ev:GameContentEvent = new GameContentEvent(GameContentEvent.EVERYTHING)
				     ev.key = swfload.vars[GameContent.GamneContentKey];
					 ev.content = swfload;
					 _gameContent.dispatchEvent(ev);
			}
			
		/**
		 * often time key==url   经常碰到把URL作为KEY，所以用的时候key和url经常是一个值.
		 * @param	key
		 * @param	url
		 * @param	param
		 */
		public function add(url:String,key:*,param:SWFLoaderVars = null):void {	  
			 if (param == null)  param = new SWFLoaderVars();
					param.vars[GameContent.GamneContentKey] = key;
			   var  swfloader:SWFLoader = new SWFLoader(url, param);			  
				  if (_data[key] == null) {
					  _data[key] = swfloader;
					  _loaderMax.append(swfloader);
				   } 
				  
		}
		
		/**
		 * swfloader 必须是加载完成的
		 * @param	key
		 * @param	swfloader
		 */
		public function addSWFLoader(key:*, swfloader:SWFLoader):void {
			 if (swfloader.status == LoaderStatus.COMPLETED) {
				  if (_data[key] == null) {
					  _data[key] = swfloader;
					   _dispatch(swfloader);
					   }
				 }
		}
			
		public function get(key:*):SWFLoader {
			 return  _data[key];
		}	
		
		public function contain(key:*):Boolean {
		     return  _data[key] != null;
		}
		
		public function remove(key:*):void {
			if (_data[key]!=null){
			    LoaderCore(_data[key]).unload();
			    LoaderCore(_data[key]).dispose();
				delete _data[key];		
			}
		}
	}

}